package org.six11.olive3.server;

import static org.six11.olive3.server.DatabaseThing.*;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.six11.olive3.picturephone.server.TodoBatch;
import org.six11.util2.Debug;
import static org.six11.olive3.server.WebActionServlet.*;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class RegisterHandler extends WebActionHandler {

  public RegisterHandler(String jspPage, WebActionServlet webActionServlet) {
    super(jspPage, webActionServlet);
  }

  /**
   * 
   */
  public void service(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    // the user hits this page in two use cases: (1) they haven't been here and would like to
    // register, or (2) they were just here and filled out a form so we need to validate it and deal
    // with the results.
    HttpSession session = req.getSession();

    String userName = req.getParameter(WebActionServlet.PARAM_USER);
    String password = req.getParameter(WebActionServlet.PARAM_PASS);
    boolean userNameThere = isValid(userName);
    boolean userNameTaken = userNameThere && findUserName(userName);
    boolean passwordThere = isValid(password);

    if (isValid(userName) && isValid(password) && addCredentials(userName, password)) {
      // start processing TODOs
      // handle this like a normal login request
      bug(userName + " / " + password + " looks OK. Sending you to login page.");
      redo(WebActionServlet.ACTION_LOGIN, req, resp, context);
    } else {
      // send the above properties to registration page.
      bug("Couldn't register you with " + userName + " / " + password);
      if (userName != null || password != null) {
        req.setAttribute(MSG_ERROR,
            "Couldn't register with that name or password. The username might be taken.");
      }
      session.setAttribute(SESSION_USER_NAME, userName);
      req.setAttribute("pass", password);
      req.setAttribute("userNameThere", userNameThere);
      req.setAttribute("userNameTaken", userNameTaken);
      req.setAttribute("passwordThere", passwordThere);
      go(req, resp, context);
    }
  }

  private boolean addCredentials(String userName, String password) {
    boolean ret = (userName != null && userName.length() > 0 && password != null && password
        .length() > 0);
    if (ret) {
      try {
        // Ensure we do not clobber somebody else.
        Map<String, String> vals = webActionServlet.getDbThing().getRow(SqlStrings.FIND_USER_BY_NAME, userName);
        if (vals.size() > 0) {
          bug("Failed to addCredentials('" + userName + "', '" + password
              + "') because user exists");
          ret = false;
        } else {
          webActionServlet.getDbThing().insertRow(SqlStrings.INSERT_USER, userName, password);
          bug("Successfully registered user " + userName);
          ret = true;
        }
      } catch (ServletException ex) {
        ex.printStackTrace();
        bug("Got exception, addCredentials('" + userName + "', '" + password + "') fails.");
        ret = false;
      }
    }
    return ret;
  }

  private boolean findUserName(String userName) {
    return false;
  }

  private void bug(String what) {
    Debug.out("RegisterHandler", what);
  }

  private boolean isValid(String userName) {
    boolean ret = (userName != null && Pattern.matches("[\\w\\p{Punct}]+", userName));
    bug("Desired username '" + userName + "' is " + (ret ? "valid" : "invalid") + ".");
    return ret;

  }

}
